<?php
/**
 * This file is part of the Anota project.
 * 2011-2012 Fernando Garcia Huerta <fgarciahue@uoc.edu>
 * 
 * UOC - FUNDAMENTOS DE INFORMÁTICA EN ENTORNOS BIOINFORMÁTICOS - PEC2
 */

/**
 * DboBase
 * 
 * Base class for all Dbo objects
 *  - manages common behaviors (save, insert and update)
 *  - defines several abstract function each child must implement.
 * 
 * @package    Anota
 * @subpackage database
 * @author     Fernando Garcia Huerta <fgarciahue@uoc.edu>
 */
abstract class DboBase {

    protected static
    $TABLE;         // database table name
    public
    $id;            // database id field of the table

    /**
     * save (insert or update) an annotation in database
     * 
     * @param Annotation $annotation
     * @param object $conn
     * @return bool
     */
    public function save($conn) {
        if ($this->id === null) {
            $result = self::insert($conn);
        } else {
            $result = self::update($conn);
        }

        return $result;
    }

    /**
     * Sets id field
     */
    abstract protected function setId($id);

    /**
     * Gets update query for the dbo object
     */
    abstract protected function getUpdateQuery();

    /**
     * gets insert query for the dbo object
     */
    abstract protected function getInsertQuery();

    /**
     * insert a row in the database
     * - object->id is filled with the value asigned by de database
     * 
     * @param object $conn
     * @return bool
     */
    protected function insert($conn) {
        $query = $this->getInsertQuery();

        if (is_null($query)) {
            return false;
        }

        $result = mysql_query($query, $conn);
        if ($result) {
            $this->setId(mysql_insert_id($conn));
        }

        return $result;
    }

    /**
     * update a row in the database
     * 
     * @param type $conn
     * @return type 
     */
    protected function update($conn) {
        $query = $this->getUpdateQuery();
        if (is_null($query)) {
            return false;
        }

        return mysql_query($query, $conn);
    }

}